// pages/zhengce/zhengce.js
let api = require("../../config/api");
let utils = require("../../utils/util");
let WxParse = require("../../wxParse/wxParse")
const app = getApp();
Page({
    totalCount:0,
    pageNum:1,
    pageSize:10,
    refreshData:true,
    /**
     * 页面的初始数据
     */
    data: {
        sw:false,
        showSuggestions:false,//是否展示“猜你想问”，第一次进入时不显示，当完成一轮对话后再显示
        activeTab: 0, // 当前激活的tab，0-智能对话，1-智能生图
        inputValue: '', // 输入框内容
        chatList: [], // 智能对话 - 对话列表
        conversationId: '', // 智能对话会话ID
        imageConversationId: '', // 智能生图会话ID（用于历史记录回显）
        conversationFileObjectId: '', // 智能生图会话中的文件对象ID（用于历史记录回显）
        difyUserId: '19890925', // 固定user，后续将从后端接口赋值
        isLoading: false, // 发送中/加载中
        isSuggestionsVisible: false, // 猜你想问是否展开
        suggestions: [ // 猜你想问的提示词
            '帮我写一篇关于春天的作文',
            '解释一下什么是人工智能',
            '推荐几本好看的书籍'
        ],
        imagePrompts: [ // 图片美化提示词
            '自然光效',
            '专业修图',
            '艺术滤镜'
        ],
        imagePromptObjects: [], // 完整的提示词对象数组（包含promptWord和promptDetail）
        beforeImages: [ // 前后对比图片 - 原图
            '/static/images/default_Picture.jpg'
        ],
        afterImages: [ // 前后对比图片 - 美化后
            '/static/images/default_Picture.jpg'
        ],
        difyLastUploadId: '', // 最近一次上传的文件ID
        difyLastLocalPath: '', // 最近一次选择的本地路径
        generationStatus: '', // 智能生图生成状态：generating-生成中，done-生成完成
        showCustomServiceButton: false, // 是否显示联系客服定制方案按钮
        // 通用确认框相关数据
        showConfirmModal: false,
        confirmModalConfig: {
            title: '提示',
            content: '请确认操作',
            confirmText: '同意',
            cancelText: '取消'
        },
        // 上传方式选择遮罩层
        showUploadModal: false,
        // 智能对话上传相关数据
        showChatUploadModal: false,
        chatUploadId: '', // 智能对话上传的图片ID
        chatUploadLocalPath: '', // 智能对话上传的本地路径
        // 历史会话相关数据
        historyConversationId: '', // 历史会话ID
        historyName: '', // 历史会话名称
        fromHistory: false, // 是否从历史页面跳转过来
        historyLoaded: false, // 历史会话是否已加载，防止重复加载
        historyType: '', // 历史会话类型：dialog-智能对话，image-智能生图
        // 智能生图历史记录相关
        historyOldPictureFileName: '', // 历史原图文件名
        historyNewPictureFileName: '', // 历史生成图文件名
        historyConversationFileObjectId: '', // 历史会话文件对象ID
        // 生图记录相关数据
        oldPictureFileName: '', // 用户上传的原始图片文件名
        newPictureFileName: '', // 生图结果图片文件名
        currentQueryWord: '', // 当前生图的提示词
        currentChatApiKey: '', // 当前使用的API Key
        // 异步任务相关数据
        currentTaskId: '', // 当前生图任务ID
        taskPollingTimer: null, // 任务轮询定时器
        isTaskPolling: false, // 是否正在轮询任务状态
        // AI思考过程相关数据
        isThinking: false, // 是否正在思考
        thinkingStartTime: 0, // 思考开始时间
        thinkingDuration: 0, // 思考时长（秒）
        thinkingContent: '', // 思考内容
        finalResponse: '', // 最终响应内容（去除思考标签）
        // 智能对话图片显示相关数据
        showPreSendImage: false, // 是否显示发送前图片
        preSendImagePath: '', // 发送前图片路径
        showPostSendImage: false, // 是否显示发送后图片
        postSendImagePath: '', // 发送后图片路径
        // 图片上传状态管理
        isUploadingChatImage: false, // 智能对话图片上传中
        isUploadingImage: false, // 智能生图图片上传中
        // 员工用户相关数据
        userRole: '', // 用户角色
        isEmployee: false, // 是否为员工用户
        // 客户信息输入遮罩层
        showCustomerInfoModal: false, // 是否显示客户信息输入遮罩层
        customerInfo: {
            name: '', // 客户姓名
            gender: '', // 客户性别
            mobile: '' // 客户电话
        },
        // 待发送的消息（员工用户需要先输入客户信息）
        pendingMessage: '', // 待发送的消息内容
        // 新对话标识
        isNewConversation: true, // 是否为新对话（首次打开页面或点击开启新对话后为true）
        // 缓存的客户信息（用于复用）
        cachedCustomerInfo: null, // 缓存的客户信息
        leftOpportunity:0
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        // 初始化提示词
        this.refreshImagePrompts();
        
        // 页面加载时初始化WebSocket状态
        this.initializeWebSocketState();
        
        // 检查是否从会话历史页面跳转过来（通过URL参数）
        if (options.fromHistory === 'true' && options.historyConversationId) {
          // 保存历史会话信息
          this.setData({
            historyConversationId: options.historyConversationId,
            historyName: options.historyName || '',
            fromHistory: true
          });
        }
        
        this.ensureAuthAndUser();
    },
    initGenerationImageData(){
      // 智能生图：清空图片和会话ID
      const updateData = { 
        // beforeImages: ['/static/images/default_Picture.jpg'], 
        // afterImages: ['/static/images/default_Picture.jpg'], 
        inputValue: '', 
        imageConversationId: '',
        showCustomServiceButton: false, // 隐藏联系客服按钮
        difyLastUploadId: '',
        difyLastLocalPath: '',
        generationStatus: '',
        // 清空生图记录相关状态
        oldPictureFileName: '',
        newPictureFileName: '',
        currentQueryWord: '',
        currentChatApiKey: '',
        conversationFileObjectId: '',
        // 清空智能生图历史记录相关状态
        historyOldPictureFileName: '',
        historyNewPictureFileName: '',
        historyConversationFileObjectId: '',
        // 清空异步任务相关状态
        currentTaskId: '',
        isTaskPolling: false,
        aiResponseContent:'',
        aiResponseContentRaw:'', // 保存原始的markdown内容，用于复制
        showAiResponseFull:false
    };
    
    // 如果是从历史页面跳转过来的，清空历史会话相关状态
    if (this.data.fromHistory) {
        updateData.fromHistory = false;
        updateData.historyConversationId = '';
        updateData.historyName = '';
        updateData.historyLoaded = false;
        updateData.historyType = '';
    }
    
    this.setData(updateData);
    // 停止任务轮询
    this.stopTaskPolling();
    try { 
        wx.setStorageSync(this.getStorageKey('image_conversation_id'), '');
    } catch (_) {}
    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
      if (this.data.sw) {
        this.setData({
          sw: false
        });
        return; // 如果sw为true，则不执行后续操作
      }
      let that = this;
      this.isLogin(function (){
          console.log('onShow 被调用');
          that.checkInfomationAndInitRole();
          that.refreshCurrentUserLeftOpportunity();
          
          // 智能初始化WebSocket相关状态（只在必要时重置）
          that.smartInitializeWebSocketState();
          
          //初始化生图数据
          that.initGenerationImageData();
          
          // 检查是否从会话历史页面跳转过来（通过本地存储）
          try {
              const fromHistory = wx.getStorageSync('fromHistory');
              const historyConversationId = wx.getStorageSync('historyConversationId');
              const historyName = wx.getStorageSync('historyName');
              const historyType = wx.getStorageSync('historyType');
              
              console.log('从本地存储读取参数:');
              console.log('fromHistory:', fromHistory);
              console.log('historyConversationId:', historyConversationId);
              console.log('historyName:', historyName);
              console.log('historyType:', historyType);
              
              if (fromHistory === 'true' && historyConversationId) {
                  console.log('从历史页面跳转过来，会话ID:', historyConversationId, '类型:', historyType);
                  
                  if (historyType === 'image') {
                      // 智能生图历史记录处理
                      that.handleImageHistory();
                  } else {
                      // 智能对话历史记录处理
                      that.handleDialogHistory(historyConversationId, historyName);
                  }
              } else {
                  // 不是从历史页面跳转，进行任务回显
                  that.resumeLatestTask();
              }
          } catch (error) {
              console.warn('读取历史会话参数失败:', error);
              // 出错时也进行任务回显
              that.resumeLatestTask();
          }
        });
    },
    checkInfomationAndInitRole(){
      wx.showLoading();
      let that = this;
			utils.request(api.getUserInfo, {}, 'POST')
				.then(function(res){
					wx.hideLoading();
					if (res.code == 0) {
						const info = res.data || {};
						const verified = (info.mobile_verify_status === 0 || info.mobile_verify_status === '0');
						if (!verified) {
							wx.showModal({ 
								title: '提示', 
                content: '为提供更好的服务，请先完善个人信息再使用此功能。',
                showCancel:false,
								complete: () => {
									// 跳转到"我的"页，引导用户授权手机号
									try { wx.switchTab({ url: '/pages/mine/mine' }); } catch (_) {}
								}
							});
							return;
						}
						// 使用后台返回的唯一 modelUserId 作为 difyUserId
						if (info.modelUserId) {
							that.setData({ difyUserId: String(info.modelUserId) });
						}
						that.setData({
              leftOpportunity:info.gen_pic_opportunity
            });
						// 直接设置用户角色信息（避免重复调用接口）
						const role = info.role;
						console.log('用户角色:', role);
						that.setData({
							userRole: role || '',
							isEmployee: role === 'employee' // 机构工作人员
						});
						that.initPage();
						// 在设置好用户ID后再加载本地缓存（按用户隔离）
						that.loadCachedConversations();
					} else {
						wx.showToast({ title: res.message || '获取用户信息失败', icon: 'none' });
					}
				})
				.catch(function(e){
					wx.hideLoading();
					wx.showToast({ title: e || '网络异常', icon: 'none' });
				});
    },
    // 恢复最近一次任务
    resumeLatestTask() {
        console.log('开始恢复最近一次任务');
        
        // 显示恢复任务的loading遮罩层
        wx.showLoading({
            title: '正在恢复任务...',
            mask: true
        });
        
        // 调用后端接口查询最近一次生图记录
        utils.request(api.getLatestPicChatRecord, {}, 'POST')
            .then(res => {
                console.log('查询最近一次生图记录结果:', res);
                
                if (res.code === "0" && res.data) {
                    const taskData = res.data;
                    console.log('任务数据:', taskData);
                    
                    // 根据任务状态进行不同的处理
                    if (taskData.status === '1') {
                        // 进行中的任务
                        this.resumeInProgressTask(taskData);
                    } else if (taskData.status === '2') {
                        // 已完成的任务
                        this.resumeCompletedTask(taskData);
                    } else {
                        // 其他状态，不进行回显
                        console.log('任务状态不是进行中或已完成，不进行回显:', taskData.status);
                        wx.hideLoading();
                    }
                } else {
                    console.log('没有找到最近一次生图记录');
                    wx.hideLoading();
                }
            })
            .catch(error => {
                console.error('查询最近一次生图记录失败:', error);
                wx.hideLoading();
            });
    },

    // 恢复进行中的任务
    resumeInProgressTask(taskData) {
        console.log('恢复进行中的任务:', taskData);
        
        // 设置任务相关数据
        this.setData({
            currentTaskId: taskData.id,
            generationStatus: 'generating',
            isLoading: true,
            activeTab: 1, // 切换到生图tab
            isNewConversation: false // 恢复的任务不是新对话
        });
        
        // 设置原图
        if (taskData.oldPictureFileName) {
            // 从完整路径中提取文件名
            const fileName = taskData.oldPictureFileName.split('/').pop();
            this.setData({
                beforeImages: [taskData.oldPictureFileName],
                oldPictureFileName: fileName
            });
        }
        
        // 设置会话文件对象ID
        if (taskData.conversationFileObjectId) {
            this.setData({
                conversationFileObjectId: taskData.conversationFileObjectId,
                difyLastUploadId:taskData.conversationFileObjectId
            });
        }
        
        // 设置AI响应内容（如果有）
        if (taskData.chatResponseContent) {
            let result = app.towxml(taskData.chatResponseContent,'markdown',{
              // theme:'dark',
              events:{
                tap:e => {
                  console.log('tap',e);
                },
                change:e => {
                  console.log('todo',e);
                }
              }
            });
            this.setData({
                aiResponseContent: result,
                aiResponseContentRaw: taskData.chatResponseContent // 保存原始内容用于复制
            });
        }
        
        // 恢复客户信息（如果是机构用户且有客户信息）
        if (this.data.isEmployee && taskData.consumerName) {
            const customerInfo = {
                name: taskData.consumerName,
                gender: taskData.consumerGender || '',
                mobile: taskData.consumerMobile || ''
            };
            console.log('恢复客户信息:', customerInfo);
            this.setData({
                customerInfo: customerInfo,
                cachedCustomerInfo: customerInfo
            });
        }
        
        // 开始轮询任务状态
        this.startTaskPolling(this.data.currentTaskId);
        
        wx.hideLoading();
        console.log('进行中任务恢复完成');
    },

    // 恢复已完成的任务
    resumeCompletedTask(taskData) {
        console.log('恢复已完成的任务:', taskData);
        
        // 设置任务相关数据
        this.setData({
            generationStatus: 'done',
            activeTab: 1, // 切换到生图tab
            isNewConversation: false // 恢复的任务不是新对话
        });
        
        // 设置原图
        if (taskData.oldPictureFileName) {
            // 从完整路径中提取文件名
            const fileName = taskData.oldPictureFileName.split('/').pop();
            this.setData({
                beforeImages: [taskData.oldPictureFileName],
                oldPictureFileName: fileName
            });
        }
        
        // 设置生成后的图片
        if (taskData.newPictureFileName) {
            this.setData({
                afterImages: [taskData.newPictureFileName]
            });
        }
        
        // 设置会话ID
        if (taskData.conversationId) {
            this.setData({
                imageConversationId:taskData.conversationId
            });
        }
        
        // 设置会话文件对象ID
        if (taskData.conversationFileObjectId) {
            this.setData({
                conversationFileObjectId: taskData.conversationFileObjectId,
                difyLastUploadId:taskData.conversationFileObjectId
            });
        }
        
        // 设置AI响应内容
        if (taskData.chatResponseContent) {
            let result = app.towxml(taskData.chatResponseContent,'markdown',{
              // theme:'dark',
              events:{
                tap:e => {
                  console.log('tap',e);
                },
                change:e => {
                  console.log('todo',e);
                }
              }
            });
            console.log(result);
            this.setData({
                aiResponseContent: result,
                aiResponseContentRaw: taskData.chatResponseContent // 保存原始内容用于复制
            });
        }
        
        // 恢复客户信息（如果是机构用户且有客户信息）
        if (this.data.isEmployee && taskData.consumerName) {
            const customerInfo = {
                name: taskData.consumerName,
                gender: taskData.consumerGender || '',
                mobile: taskData.consumerMobile || ''
            };
            console.log('恢复客户信息:', customerInfo);
            this.setData({
                customerInfo: customerInfo,
                cachedCustomerInfo: customerInfo
            });
        }
        
        wx.hideLoading();
        console.log('已完成任务恢复完成');
    },
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {
        console.log('onHide 被调用');
        
    },

    // 格式化时间为 yyyy-MM-dd HH:mm:ss 格式
    formatDateTime(date) {
        try {
            if (!date) {
                date = new Date();
            }
            
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            const seconds = String(date.getSeconds()).padStart(2, '0');
            
            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        } catch (e) {
            console.error('时间格式化失败:', e);
            return new Date().toISOString().slice(0, 19).replace('T', ' ');
        }
    },

    // 智能初始化WebSocket相关状态（只在必要时重置）
    smartInitializeWebSocketState() {
        console.log('智能初始化WebSocket相关状态...');
        
        try {
            // 检查是否有正在进行的操作
            const isGenerating = this.data.generationStatus === 'generating';
            const isLoading = this.data.isLoading;
            const hasActiveWebSocket = this.ws && this.ws.readyState === WebSocket.OPEN;
            
            console.log('当前状态检查:');
            console.log('- 是否正在生图:', isGenerating);
            console.log('- 是否正在加载:', isLoading);
            console.log('- WebSocket是否活跃:', hasActiveWebSocket);
            
            // 如果有正在进行的操作，检查WebSocket连接状态
            if (isGenerating || isLoading) {
                console.log('检测到正在进行的操作');
                
                // 检查WebSocket连接是否断开
                if (!hasActiveWebSocket) {
                    console.log('WebSocket连接已断开，尝试重新连接以继续操作');
                    this.reconnectWebSocketForOngoingOperation();
                    return;
                } else {
                    console.log('WebSocket连接正常，跳过状态重置');
                    return;
                }
            }
            
            // 检查是否从历史页面跳转过来
            const fromHistory = wx.getStorageSync('fromHistory');
            if (fromHistory === 'true') {
                console.log('从历史页面跳转，需要重置WebSocket状态');
                this.initializeWebSocketState();
                return;
            }
            
            // 检查WebSocket连接是否异常
            if (this.ws && this.ws.readyState !== WebSocket.OPEN && this.ws.readyState !== WebSocket.CONNECTING) {
                console.log('WebSocket连接异常，需要重置');
                this.initializeWebSocketState();
                return;
            }
            
            console.log('无需重置WebSocket状态');
        } catch (e) {
            console.error('智能初始化WebSocket状态失败:', e);
            // 出错时执行完整重置
            this.initializeWebSocketState();
        }
    },

    // 初始化WebSocket相关状态（完整重置）
    initializeWebSocketState() {
        console.log('完整初始化WebSocket相关状态...');
        
        try {
            // 关闭现有的WebSocket连接
            if (this.ws) {
                console.log('关闭现有WebSocket连接');
                this.ws.close();
                this.ws = null;
            }
            
            // 重置WebSocket相关状态
            this._wsMessageBound = false;
            this._streamCtx = null;
            this.lastMessageId = null;
            
            // 重置页面状态（但保留联系客服按钮状态，除非是新的生图会话）
            this.setData({
                isLoading: false,
                generationStatus: ''
                // 不重置showCustomServiceButton，保持当前状态
            });
            
            console.log('WebSocket状态初始化完成');
        } catch (e) {
            console.error('初始化WebSocket状态失败:', e);
        }
    },

    // 为进行中的操作重新连接WebSocket
    reconnectWebSocketForOngoingOperation() {
        console.log('为进行中的操作重新连接WebSocket...');
        
        try {
            // 获取当前会话信息
            const currentConversationId = this.data.currentConversationId || this.data.historyConversationId;
            const currentQueryWord = this.data.currentQueryWord;
            const currentChatApiKey = this.data.currentChatApiKey;
            const activeTab = this.data.activeTab;
            
            console.log('重新连接参数:');
            console.log('- 会话ID:', currentConversationId);
            console.log('- 查询词:', currentQueryWord);
            console.log('- 当前标签:', activeTab);
            
            if (!currentConversationId || !currentQueryWord) {
                console.warn('缺少必要的会话信息，无法重新连接');
                // 重置状态，让用户重新开始
                this.setData({
                    generationStatus: '',
                    isLoading: false,
                    showCustomServiceButton: false
                });
                wx.showToast({
                    title: '连接已断开',
                    icon: 'none',
                    duration: 2000
                });
                return;
            }
            
            // 重新建立WebSocket连接
            console.log('重新建立WebSocket连接...');
            this.ensureWebSocketConnected();
            
            // 重新发送请求（智能生图模式）
            if (activeTab === 1) {
                console.log('重新发送智能生图请求...');
                this.callDifyChat(currentQueryWord, 1);
            }
            
        } catch (e) {
            console.error('重新连接WebSocket失败:', e);
            // 重置状态
            this.setData({
                generationStatus: '',
                isLoading: false,
                showCustomServiceButton: false
            });
            wx.showToast({
                title: '连接失败，请重新开始',
                icon: 'none',
                duration: 2000
            });
        }
    },

    // 检查WebSocket连接状态
    checkWebSocketStatus() {
        if (!this.ws) {
            return 'DISCONNECTED';
        }
        
        switch (this.ws.readyState) {
            case WebSocket.CONNECTING:
                return 'CONNECTING';
            case WebSocket.OPEN:
                return 'OPEN';
            case WebSocket.CLOSING:
                return 'CLOSING';
            case WebSocket.CLOSED:
                return 'CLOSED';
            default:
                return 'UNKNOWN';
        }
    },

    // 处理智能对话历史记录
    handleDialogHistory(historyConversationId, historyName) {
        // 保存历史会话信息
        this.setData({
            historyConversationId: historyConversationId,
            historyName: historyName || '',
            fromHistory: true,
            historyType: 'dialog'
        });
        
        // 清除本地存储中的标记，避免重复处理
        wx.removeStorageSync('fromHistory');
        wx.removeStorageSync('historyConversationId');
        wx.removeStorageSync('historyName');
        wx.removeStorageSync('historyType');
        
        // 如果用户已经认证完成，直接加载历史会话
        if (this.data.difyUserId && this.data.difyUserId !== '19890925') {
            console.log('用户已认证，直接加载历史会话');
            this.loadHistoryConversation();
        } else {
            console.log('用户未认证或使用默认ID，等待认证完成后加载');
            // 重新触发用户认证流程
            this.ensureAuthAndUser();
        }
    },

    // 处理智能生图历史记录
    handleImageHistory() {
        try {
            const historyOldPictureFileName = wx.getStorageSync('historyOldPictureFileName');
            const historyNewPictureFileName = wx.getStorageSync('historyNewPictureFileName');
            const historyConversationFileObjectId = wx.getStorageSync('historyConversationFileObjectId');
            
            console.log('智能生图历史记录参数:');
            console.log('historyOldPictureFileName:', historyOldPictureFileName);
            console.log('historyNewPictureFileName:', historyNewPictureFileName);
            console.log('historyConversationFileObjectId:', historyConversationFileObjectId);
            
            // 保存智能生图历史记录信息
            this.setData({
                historyConversationId: wx.getStorageSync('historyConversationId'),
                historyName: wx.getStorageSync('historyName'),
                fromHistory: true,
                historyType: 'image',
                historyOldPictureFileName: historyOldPictureFileName || '',
                historyNewPictureFileName: historyNewPictureFileName || '',
                historyConversationFileObjectId: historyConversationFileObjectId || '',
                // 自动切换到智能生图tab
                activeTab: 1
            });
            
            // 清除本地存储中的标记，避免重复处理
            wx.removeStorageSync('fromHistory');
            wx.removeStorageSync('historyConversationId');
            wx.removeStorageSync('historyName');
            wx.removeStorageSync('historyType');
            wx.removeStorageSync('historyOldPictureFileName');
            wx.removeStorageSync('historyNewPictureFileName');
            wx.removeStorageSync('historyConversationFileObjectId');
            
            // 回显智能生图历史记录（不调用loadHistoryConversation）
            this.loadImageHistory();
        } catch (error) {
            console.warn('处理智能生图历史记录失败:', error);
        }
    },
    getImageNameFromUrl(url) {
      try {
          // 分割路径并获取最后一部分
          const pathParts = url.split('/');
          const fileName = pathParts[pathParts.length - 1];
          
          // 检查是否为空路径
          return fileName || null;
      } catch (error) {
          console.error('无效的URL:', error);
          return null;
      }
  },
    // 加载智能生图历史记录
    loadImageHistory() {
        console.log('开始加载智能生图历史记录');
        
        const { 
            historyConversationId, 
            historyOldPictureFileName, 
            historyNewPictureFileName, 
            historyConversationFileObjectId 
        } = this.data;
        
        // 获取任务状态和AI响应内容
        const historyTaskStatus = wx.getStorageSync('historyTaskStatus') || '2';
        const historyChatResponseContent = wx.getStorageSync('historyChatResponseContent') || '';
        
        console.log('历史记录参数:');
        console.log('conversationId:', historyConversationId);
        console.log('conversationFileObjectId:', historyConversationFileObjectId);
        console.log('oldPictureFileName:', historyOldPictureFileName);
        console.log('newPictureFileName:', historyNewPictureFileName);
        console.log('任务状态:', historyTaskStatus);
        console.log('AI响应内容:', historyChatResponseContent);
        
        // 设置智能生图会话ID和文件对象ID（用于继续对话）
        this.setData({
            imageConversationId: historyConversationId,  // 历史会话的会话ID
            conversationFileObjectId: historyConversationFileObjectId,  // 历史会话的文件附件ID
            difyLastUploadId: historyConversationFileObjectId,  // 用于继续对话的文件ID
            // 确保智能生图tab被选中
            activeTab: 1
        });
        
        // 根据任务状态设置不同的回显状态
        let generationStatus = 'done';
        let showCustomServiceButton = true;
        let aiResponseContent = '';
        let beforeImages = [];
        let afterImages = [];
        let oldPictureFileName = '';
        if (historyTaskStatus === '1') {
            // 执行中：显示旧图和loading状态
            generationStatus = 'generating';
            showCustomServiceButton = false;
            beforeImages = historyOldPictureFileName ? [historyOldPictureFileName] : [];
            afterImages = [];  // 执行中不显示生成图
            console.log('任务执行中，显示loading状态');
        } else if (historyTaskStatus === '2') {
            // 已完成：显示对比图和AI响应
            generationStatus = 'done';
            showCustomServiceButton = true;
            aiResponseContent = historyChatResponseContent;
            beforeImages = historyOldPictureFileName ? [historyOldPictureFileName] : [];
            afterImages = historyNewPictureFileName ? [historyNewPictureFileName] : [];
            oldPictureFileName = this.getImageNameFromUrl( historyOldPictureFileName );
            console.log('任务已完成，显示对比图和AI响应');
        } else if (historyTaskStatus === '3') {
            // 失败：只显示旧图
            generationStatus = '';
            showCustomServiceButton = false;
            beforeImages = historyOldPictureFileName ? [historyOldPictureFileName] : [];
            afterImages = [];  // 失败不显示生成图
            console.log('任务失败，只显示原图');
        }
        let result = app.towxml(aiResponseContent,'markdown',{
          // theme:'dark',
          events:{
            tap:e => {
              console.log('tap',e);
            },
            change:e => {
              console.log('todo',e);
            }
          }
        });
        // 回显对比图片和状态
        this.setData({
            beforeImages: beforeImages,  // oldPictureFileName放在beforeImages中
            afterImages: afterImages,     // newPictureFileName放在afterImages中
            oldPictureFileName:oldPictureFileName,//原始文件名，恢复历史时，再创建任务，要回显记录中的oldPicture。
            showCustomServiceButton: showCustomServiceButton,
            generationStatus: generationStatus,
            aiResponseContent: result,  // chatResponseContent回显AI响应内容
            aiResponseContentRaw: aiResponseContent, // 保存原始内容用于复制
            // 确保智能生图tab被选中
            activeTab: 1
        });
        
        console.log('图片显示状态:');
        console.log('beforeImages:', beforeImages);
        console.log('afterImages:', afterImages);
        console.log('aiResponseContent:', aiResponseContent);
        console.log('activeTab:', 1);
        
        // 如果任务正在进行中，需要重新开始轮询
        if (historyTaskStatus === '1') {
            console.log('检测到进行中的任务，需要重新开始轮询');
            // 从本地存储获取任务ID
            const historyTaskId = wx.getStorageSync('currentTaskId');
            if (historyTaskId) {
                console.log('恢复轮询任务:', historyTaskId);
                this.setData({
                    currentTaskId: historyTaskId,
                    isLoading: true
                });
                this.startTaskPolling();
            } else {
                console.log('未找到任务ID，无法恢复轮询');
                // 设置为生成中状态，但不开始轮询
                this.setData({
                    generationStatus: 'generating',
                    isLoading: true
                });
            }
        }
        
        // 清除本地存储中的历史记录参数
        wx.removeStorageSync('historyTaskStatus');
        wx.removeStorageSync('historyChatResponseContent');
        wx.removeStorageSync('fromHistory');
        wx.removeStorageSync('historyConversationId');
        wx.removeStorageSync('historyName');
        wx.removeStorageSync('historyType');
        wx.removeStorageSync('historyOldPictureFileName');
        wx.removeStorageSync('historyNewPictureFileName');
        wx.removeStorageSync('historyConversationFileObjectId');
        wx.removeStorageSync('historyTaskId');
        
        console.log('智能生图历史记录加载完成');
        console.log('原图:', beforeImages);
        console.log('生成图:', afterImages);
        console.log('任务状态:', historyTaskStatus);
        console.log('AI响应内容:', aiResponseContent);
    },

    // 复制AI响应内容到剪切板（AI测脸模块）
    copyAiResponseContent(){
        const rawContent = this.data.aiResponseContentRaw;
        if(!rawContent){
            wx.showToast({title:'暂无内容',icon:'none'});
            return;
        }
        wx.setClipboardData({
            data: rawContent,
            success: () => {
                wx.showToast({
                    title: '已复制到剪切板',
                    icon: 'success',
                    duration: 2000
                });
            },
            fail: () => {
                wx.showToast({
                    title: '复制失败',
                    icon: 'none'
                });
            }
        });
    },

    // 复制AI咨询消息到剪切板（AI咨询模块）
    copyAiConsultMessage(e){
        const index = e.currentTarget.dataset.index;
        const { chatList } = this.data;
        
        if(!chatList || chatList.length === 0 || index === undefined || index < 0 || index >= chatList.length){
            wx.showToast({title:'暂无内容',icon:'none'});
            return;
        }
        
        const message = chatList[index];
        if(!message || message.type !== 'ai' || !message.content){
            wx.showToast({title:'暂无AI响应内容',icon:'none'});
            return;
        }
        
        wx.setClipboardData({
            data: message.content,
            success: () => {
                wx.showToast({
                    title: '已复制到剪切板',
                    icon: 'success',
                    duration: 2000
                });
            },
            fail: () => {
                wx.showToast({
                    title: '复制失败',
                    icon: 'none'
                });
            }
        });
    },
    // 打开AI响应全屏查看
    openAiResponseFull(){
        if(!this.data.aiResponseContent){
            wx.showToast({title:'暂无内容',icon:'none'});
            return;
        }
        this.setData({ showAiResponseFull:true });
    },
    // 关闭AI响应全屏查看
    closeAiResponseFull(){
        this.setData({ showAiResponseFull:false });
    },

    /**
     * 初始化页面
     */
    initPage() {
        // 初始化对话列表
        this.setData({
            chatList: []
        });
    },

	// 登录鉴权 + 获取用户信息 + 校验手机号授权 + 设置 difyUserId
	ensureAuthAndUser() {
		let that = this;
		this.isLogin(function (){
			that.checkInfomationAndInitRole();
		});
	},

	// 生成存储键（按用户区分，避免账号串数据）
	getStorageKey(suffix) {
		const user = this.data && this.data.difyUserId ? this.data.difyUserId : 'default';
		return `zhengce_chat_${suffix}_${user}`;
	},


	/**
	 * 显示客户信息输入遮罩层
	 */
	showCustomerInfoModal() {
		this.setData({
			showCustomerInfoModal: true,
			customerInfo: {
				name: '',
				gender: '',
				mobile: ''
			}
		});
	},

	/**
	 * 隐藏客户信息输入遮罩层
	 */
	hideCustomerInfoModal() {
		this.setData({
			showCustomerInfoModal: false
		});
	},

	/**
	 * 客户信息遮罩层点击事件（只有点击遮罩层背景才关闭）
	 */
	onCustomerInfoMaskTap(e) {
		// 只有点击遮罩层本身才关闭，点击模态框内容不关闭
		if (e.target === e.currentTarget) {
			this.hideCustomerInfoModal();
		}
	},

	/**
	 * 客户信息模态框点击事件（阻止事件冒泡）
	 */
	onCustomerInfoModalTap(e) {
		// 阻止事件冒泡，防止关闭遮罩层
		// 在微信小程序中，使用 e.stopPropagation() 或 e.preventDefault()
		if (e.stopPropagation) {
			e.stopPropagation();
		}
	},

	/**
	 * 客户信息输入变化
	 */
	onCustomerInfoChange(e) {
		const { field } = e.currentTarget.dataset;
		const { value } = e.detail;
		this.setData({
			[`customerInfo.${field}`]: value
		});
	},

	/**
	 * 性别选择
	 */
	onGenderSelect(e) {
		const { gender } = e.currentTarget.dataset;
		this.setData({
			'customerInfo.gender': gender
		});
	},

	/**
	 * 确认客户信息并发送消息
	 */
	confirmCustomerInfo() {
		const { customerInfo, pendingMessage } = this.data;
		
		// 验证必填字段
		if (!customerInfo.name.trim()) {
			wx.showToast({
				title: '请输入客户姓名',
				icon: 'none'
			});
			return;
		}
		
		if (!customerInfo.gender) {
			wx.showToast({
				title: '请选择客户性别',
				icon: 'none'
			});
			return;
		}
		
		if (!customerInfo.mobile.trim()) {
			wx.showToast({
				title: '请输入客户电话',
				icon: 'none'
			});
			return;
		}
		
		// 验证手机号格式
		const mobileRegex = /^1[3-9]\d{9}$/;
		if (!mobileRegex.test(customerInfo.mobile.trim())) {
			wx.showToast({
				title: '请输入正确的手机号',
				icon: 'none'
			});
			return;
		}
		
		// 保存客户信息到缓存
		const customerInfoData = {
			name: customerInfo.name,
			gender: customerInfo.gender,
			mobile: customerInfo.mobile
		};
		
		this.setData({
			cachedCustomerInfo: customerInfoData
		});
		
		// 保存客户信息到本地缓存
		try {
			wx.setStorageSync(this.getStorageKey('customer_info'), customerInfoData);
			console.log('客户信息已保存到本地缓存');
		} catch (e) {
			console.warn('保存客户信息到本地缓存失败:', e);
		}
		
		// 隐藏遮罩层
		this.hideCustomerInfoModal();
		
		// 清空待发送消息
		this.setData({ pendingMessage: '' });
		
		// 显示确认提示框后创建生图任务（员工用户已输入客户信息）
		if (pendingMessage) {
			this.showImageTaskConfirmModal(() => {
				this.createImageGenerationTaskWithCustomerInfo(pendingMessage);
			});
		}
	},

	/**
	 * 显示生图任务确认提示框
	 */
	showImageTaskConfirmModal(callback) {
    let leftOpportunity = this.data.leftOpportunity;
		const modal = utils.showConfirmModal({
			title: '确认生图',
			content: '此操作将会消耗一次AI测图机会，是否确认开始？当前剩余：'+leftOpportunity+' 次',
			confirmText: '确认',
			cancelText: '取消',
			onConfirm: () => {
				console.log('用户确认开始生图任务');
				if (callback && typeof callback === 'function') {
					callback();
				}
			},
			onCancel: () => {
				console.log('用户取消了生图任务');
			}
		});
	},

	/**
	 * 发送待发送的消息
	 */
	sendPendingMessage() {
		const { pendingMessage } = this.data;
		if (pendingMessage) {
			// 清空待发送消息
			this.setData({ pendingMessage: '' });
			
			// 发送消息
			this.sendSuggestionMessage(pendingMessage);
		}
	},

	/**
	 * 创建生图任务（员工用户已输入客户信息）
	 */
	createImageGenerationTaskWithCustomerInfo(suggestion) {
		const { customerInfo, difyUserId, currentChatApiKey, oldPictureFileName, difyLastUploadId } = this.data;
		
		console.log('创建异步生图任务（员工用户）:', { suggestion, customerInfo });
		
		// 显示加载状态
		this.setData({ 
			isLoading: true,
			generationStatus: 'generating',
			showCustomServiceButton: false,
			isNewConversation: false // 标记为非新对话
		});
		
		// 准备请求数据
		const requestData = {
			conversationId: this.data.imageConversationId || '',
			conversationFileObjectId: difyLastUploadId,
			queryWord: suggestion,
			oldPictureFileName: oldPictureFileName,
			consumerName: customerInfo.name,
			consumerGender: customerInfo.gender,
			consumerMobile: customerInfo.mobile
		};
		
		// 调用后端创建任务接口
		wx.request({
			url: api.base + '/api/InterfaceManageRestService/v1/interfaceManage/createImageTask',
			method: 'POST',
			header: {
				'Content-Type': 'application/x-www-form-urlencoded',
				'X-MiniProgram-Token': wx.getStorageSync('token')
			},
			data: requestData,
			success: (res) => {
				console.log('创建任务响应:', res);
				if (res.data && res.data.code === "0") {
					const taskId = res.data.data;
					console.log('任务创建成功，任务ID:', taskId);
					
					// 保存任务ID并开始轮询
					this.setData({ currentTaskId: taskId });
					
					// 保存任务ID到本地存储，用于页面切换时恢复
					wx.setStorageSync('currentTaskId', taskId);
					
					this.startTaskPolling(taskId);
				} else {
					console.error('创建任务失败:', res.data);
					wx.showToast({ 
						title: res.data.message || '创建任务失败', 
						icon: 'none' 
					});
					this.setData({ 
						isLoading: false,
						generationStatus: ''
					});
				}
			},
			fail: (error) => {
				console.error('创建任务请求失败:', error);
				wx.showToast({ 
					title: '网络请求失败', 
					icon: 'none' 
				});
				this.setData({ 
					isLoading: false,
					generationStatus: ''
				});
			}
		});
	},

	// 读取本地缓存的会话ID与对话记录（仅保留最近20条）并回显
	loadCachedConversations() {
		try {
			console.log('loadCachedConversations 被调用');
			console.log('fromHistory:', this.data.fromHistory);
			console.log('historyConversationId:', this.data.historyConversationId);
			console.log('historyType:', this.data.historyType);
			
			// 如果是从历史页面跳转过来，根据类型处理
			if (this.data.fromHistory && this.data.historyConversationId) {
				if (this.data.historyType === 'image') {
					console.log('检测到智能生图历史记录，跳过智能对话加载');
					return; // 智能生图历史记录不需要加载智能对话
				} else {
					console.log('检测到智能对话历史会话，开始加载历史聊天记录...');
					this.loadHistoryConversation();
					return;
				}
			}
			
			const dialogConvKey = this.getStorageKey('dialog_conversation_id');
			const imageConvKey = this.getStorageKey('image_conversation_id');
			const dialogKey = this.getStorageKey('dialog_list');
			const imageKey = this.getStorageKey('image_list');
			const customerInfoKey = this.getStorageKey('customer_info');
			const cachedDialogConvId = wx.getStorageSync(dialogConvKey) || '';
			const cachedImageConvId = wx.getStorageSync(imageConvKey) || '';
			const cachedDialog = wx.getStorageSync(dialogKey) || [];
			const cachedImage = wx.getStorageSync(imageKey) || [];
			const cachedCustomerInfo = wx.getStorageSync(customerInfoKey) || null;
			const dialogLast20 = Array.isArray(cachedDialog) ? cachedDialog.slice(-20) : [];
			const imageLast20 = Array.isArray(cachedImage) ? cachedImage.slice(-20) : [];
			
			// 设置缓存数据
			const updateData = {
				conversationId: cachedDialogConvId || this.data.conversationId,
				imageConversationId: cachedImageConvId || this.data.imageConversationId,
				chatList: dialogLast20,
				imageChatList: imageLast20
			};
			
			// 恢复缓存的客户信息
			if (cachedCustomerInfo) {
				updateData.cachedCustomerInfo = cachedCustomerInfo;
				console.log('已恢复缓存的客户信息:', cachedCustomerInfo);
			}
			
			this.setData(updateData);
			// 回显后滚动到底部
			this.scrollToBottom();
		} catch (e) {
			console.warn('loadCachedConversations failed', e);
		}
	},

	// 加载历史会话的聊天记录
	loadHistoryConversation() {
		const that = this;
		const conversationId = this.data.historyConversationId;
		
		console.log('loadHistoryConversation 被调用，会话ID:', conversationId);
		console.log('当前用户ID:', this.data.difyUserId);
		console.log('历史会话是否已加载:', this.data.historyLoaded);
		
		// 防止重复加载
		if (this.data.historyLoaded) {
			console.log('历史会话已加载，跳过重复加载');
			return;
		}
		
		if (!conversationId) {
			console.warn('No history conversation ID provided');
			return;
		}
		
		if (!this.data.difyUserId || this.data.difyUserId === '19890925') {
			console.warn('用户ID未设置或使用默认ID，无法加载历史会话');
			wx.showToast({
				title: '用户信息未加载完成',
				icon: 'none'
			});
			return;
		}
		
		// 设置加载标志，防止重复加载
		this.setData({ historyLoaded: true });
		
		wx.showLoading({ title: '加载历史会话...' });
		
		// 调用Dify API获取历史会话的聊天记录
		const base = api.dify && api.dify.base ? api.dify.base : '';
		const url = base + '/messages';
		const apiKey = api.dify.dialogApiKey; // 使用智能对话的API Key
		const headers = {
			'Authorization': 'Bearer ' + apiKey
		};
		
		// 请求参数
		const params = {
			conversation_id: conversationId,
			user: this.data.difyUserId,
			limit: 50 // 获取最近50条消息
		};
		
		console.log('调用messages接口，参数:', params);
		
		wx.request({
			url: url,
			method: 'GET',
			header: headers,
			data: params,
			success: (res) => {
				wx.hideLoading();
				try {
					if (res.statusCode === 200 && res.data && Array.isArray(res.data.data)) {
						const messages = res.data.data || [];
						// 将历史消息转换为聊天列表格式
						const chatList = [];
						
						messages.forEach(msg => {
							// 格式化时间戳
							const formatTime = (timestamp) => {
								try {
									const date = new Date(timestamp * 1000); // Dify API返回的是秒级时间戳
									return that.formatDateTime(date);
								} catch (e) {
									return that.formatDateTime(new Date());
								}
							};
							
							// 根据Dify API文档，消息结构包含query(用户输入)和answer(AI回复)
							// 先添加用户消息（如果存在）
							if (msg.query) {
								chatList.push({
									type: 'user',
									content: msg.query,
									time: formatTime(msg.created_at || Date.now())
								});
							}
							
							// 再添加AI回复（如果存在）
							if (msg.answer) {
								chatList.push({
									type: 'ai',
									content: msg.answer,
									time: formatTime(msg.created_at || Date.now())
								});
							}
						});
						
						// 对历史消息中的AI回复进行towxml渲染
						const processedChatList = chatList.map(item => {
							if (item.type === 'ai' && item.content) {
								try {
									const result = app.towxml(item.content, 'markdown', {
										events: {
											tap: e => {
												console.log('towxml tap', e);
											},
											change: e => {
												console.log('towxml change', e);
											}
										}
									});
									return Object.assign({}, item, { towxmlNodes: result });
								} catch (e) {
									console.warn('历史消息towxml渲染失败', e);
									return item;
								}
							}
							return item;
						});
						
						// 设置历史会话ID和聊天记录
						that.setData({
							conversationId: conversationId, // 使用历史会话ID
							chatList: processedChatList,
							activeTab: 0 // 确保切换到智能对话tab
						});
						
						// 回显后滚动到底部
						that.scrollToBottom();
						
						wx.showToast({
							title: '历史会话加载完成',
							icon: 'success'
						});
					} else {
						console.warn('loadHistoryConversation unexpected response', res);
						wx.showToast({
							title: '加载历史会话失败',
							icon: 'none'
						});
					}
				} catch (e) {
					console.warn('parse history conversation failed', e);
					wx.showToast({
						title: '解析历史会话失败',
						icon: 'none'
					});
				}
			},
			fail: (err) => {
				wx.hideLoading();
				console.warn('loadHistoryConversation failed', err);
				wx.showToast({
					title: '加载历史会话失败',
					icon: 'none'
				});
			}
		});
	},

	// 保存当前 tab 的对话记录（仅最近20条）
	saveChatListToCache() {
		try {
			const isImageTab = this.data.activeTab === 1;
			const key = this.getStorageKey(isImageTab ? 'image_list' : 'dialog_list');
			const list = isImageTab ? this.data.imageChatList : this.data.chatList;
			const last20 = Array.isArray(list) ? list.slice(-20) : [];
			wx.setStorageSync(key, last20);
		} catch (e) {
			console.warn('saveChatListToCache failed', e);
		}
	},

	// 保存会话ID（根据当前tab分别保存）
	saveConversationIdToCache(conversationId) {
		try {
			const isImageTab = this.data.activeTab === 1;
			const convKey = this.getStorageKey(isImageTab ? 'image_conversation_id' : 'dialog_conversation_id');
			wx.setStorageSync(convKey, conversationId || '');
		} catch (e) {
			console.warn('saveConversationIdToCache failed', e);
		}
    },

    /**
     * tab切换
     */
    onTabChange(e) {
        const index = parseInt(e.currentTarget.dataset.index);
        console.log('Tab changed from', this.data.activeTab, 'to', index);
        
        // 完全重置WebSocket相关状态，只保留聊天记录
        this.resetWebSocketState();
        
        // 切换tab
        this.setData({
            activeTab: index,
            isLoading: false
        });
        
        console.log('Tab switch completed, current tab:', index);
    },

    /**
     * 重置WebSocket相关状态（保留聊天记录）
     */
    resetWebSocketState() {
        console.log('Resetting WebSocket state...');
        
        // 清理流上下文
        if (this._streamCtx) {
            console.log('Clearing stream context:', this._streamCtx);
            this._streamCtx = null;
        }
        
        // 重置loading状态
        this.setData({ isLoading: false });
        
        // 清理WebSocket连接状态（但不断开连接）
        this._wsMessageBound = false;
        
        // 重置消息ID
        this.lastMessageId = null;
        
        console.log('WebSocket state reset completed');
    },

    /**
     * 输入框内容变化
     */
    onInputChange(e) {
        this.setData({
            inputValue: e.detail.value
        });
    },

    /**
     * 发送消息
     */
    sendMessage() {
      let that = this;
      this.isLogin(function (){
        that.checkInfomationAndInitRole();
        const { inputValue, activeTab, difyLastUploadId, isLoading, chatUploadId } = that.data;
        
        // 如果正在加载中，禁止发送
        if (isLoading) {
            wx.showToast({
                title: 'AI正在思考中，请稍候...',
                icon: 'none'
            });
            return;
        }
        
        // 智能对话：如果上传了图片但没有输入文字，提示用户输入
        if (activeTab === 0 && chatUploadId && !inputValue.trim()) {
            wx.showToast({
                title: '请输入想说的话',
                icon: 'none'
            });
            return;
        }
        
        // 智能对话：如果没有上传图片也没有输入文字，提示用户输入
        if (activeTab === 0 && !chatUploadId && !inputValue.trim()) {
            wx.showToast({
                title: '请输入内容',
                icon: 'none'
            });
            return;
        }

        // 智能生图：校验必须同时上传照片和输入文字
        if (activeTab === 1) {
            if (!difyLastUploadId && !inputValue.trim()) {
                wx.showToast({ title: '请先上传照片并输入美化要求', icon: 'none' });
                return;
            } else if (!difyLastUploadId) {
            wx.showToast({ title: '请先上传照片', icon: 'none' });
            return;
            } else if (!inputValue.trim()) {
                wx.showToast({ title: '请输入图片美化要求', icon: 'none' });
                return;
            }
            
            // 员工用户需要检查客户信息
            if (that.data.isEmployee) {
                const { cachedCustomerInfo } = that.data;
                
                if (cachedCustomerInfo) {
                    // 有缓存的客户信息，直接复用
                    console.log('复用缓存的客户信息:', cachedCustomerInfo);
                    that.setData({ customerInfo: cachedCustomerInfo });
                } else {
                    // 没有缓存信息，需要输入客户信息
                    that.setData({ pendingMessage: inputValue });
                    that.showCustomerInfoModal();
                    return;
                }
            }
        }

        if (activeTab === 0) {
            // 智能对话：暂存用户消息，等待WebSocket响应确认后再显示
            const userMessage = {
                type: 'user',
                content: inputValue,
                    time: that.formatDateTime(new Date()),
                    hasImage: chatUploadId ? true : false, // 标记是否有图片
                    imagePath: chatUploadId ? that.data.preSendImagePath : '' // 图片路径
            };
                        
            // 暂存用户消息，不立即添加到聊天列表
            that._pendingUserMessage = userMessage;
            // 处理图片显示状态
            if (chatUploadId) {
                // 有图片：移动到左上角显示，隐藏右下角图片
                that.setData({ 
                    inputValue: '',
                    showPreSendImage: false, // 隐藏右下角图片
                    showPostSendImage: true, // 显示左上角图片
                    postSendImagePath: that.data.preSendImagePath,
                    preSendImagePath: '' // 清空右下角图片路径
                });
            } else {
                // 无图片：正常处理
                that.setData({ 
                    inputValue: ''
                });
            }
        } else {
            // 智能生图：不显示用户消息，直接清空输入框
            that.setData({ inputValue: '' });
        }

        // 智能生图：保存当前生图的相关信息
        if (activeTab === 1) {
          that.setData({
                currentQueryWord: inputValue,
                currentChatApiKey: api.dify && api.dify.apiKey ? api.dify.apiKey : '',
                showCustomServiceButton: false // 新消息发送时隐藏联系客服按钮
            });
        }

        that.callDifyChat(inputValue, activeTab);
        
        // 智能对话发送后清空图片上传状态
        if (activeTab === 0) {
            that.setData({ 
                chatUploadId: '', 
                chatUploadLocalPath: '',
                showPostSendImage: false, // 隐藏左上角图片
                postSendImagePath: '' // 清空左上角图片路径
            });
        }
      });
    },

    /**
     * 模拟AI回复
     */
    simulateAIResponse(userInput, tabType) {},

    /**
     * 生成对话回复
     */
    generateChatResponse(input) {
        const responses = [
            '这是一个很有趣的问题，让我来为您详细解答...',
            '根据您的问题，我建议您可以考虑以下几个方面...',
            '我理解您的需求，基于我的知识库，我可以为您提供以下建议...',
            '这是一个很好的问题，让我从多个角度来分析一下...'
        ];
        return responses[Math.floor(Math.random() * responses.length)];
    },

    /**
     * 流式输出回复
     */
    streamResponse(response) {
        let currentText = '';
        const isImageTab = this.data.activeTab === 1;
        const startIndex = isImageTab ? this.data.imageChatList.length : this.data.chatList.length;
        // 先放入一个空的AI消息占位
        const now = this.formatDateTime(new Date());
        if (isImageTab) {
            this.setData({ imageChatList: [...this.data.imageChatList, { type: 'ai', content: '', time: now }] });
        } else {
            this.setData({ chatList: [...this.data.chatList, { type: 'ai', content: '', time: now }] });
        }
        const interval = setInterval(() => {
            if (currentText.length < response.length) {
                currentText += response[currentText.length];
                if (isImageTab) {
                    const updated = [...this.data.imageChatList];
                    updated[startIndex] = { type: 'ai', content: currentText, time: now };
                    this.setData({ imageChatList: updated });
                } else {
                    const updated = [...this.data.chatList];
                    updated[startIndex] = { type: 'ai', content: currentText, time: now };
                    this.setData({ chatList: updated });
                }
                // this.scrollToBottom();
            } else {
                clearInterval(interval);
            }
        }, 15);
    },

    // 滚动到底部的辅助方法
    scrollToBottom() {
        // 通过改变 scrollTop 触发滚动（需要在 wxml 的 scroll-view 绑定 scroll-top）
        this.setData({ scrollTop: Date.now() });
    },

    /**
     * 调用 Dify Chat API（blocking 模式），前端做伪流式渲染
     */
    callDifyChat(query, tabType) {
        const { difyUserId, conversationId, imageConversationId, difyLastUploadId, fromHistory, historyConversationId } = this.data;
        
        
        // 智能对话：确定使用的会话ID（历史会话优先）
        let currentConversationId = conversationId;
        if (tabType === 0 && fromHistory && historyConversationId) {
            currentConversationId = historyConversationId;
        }
        
        // 智能生图走异步任务模式
        if (tabType === 1) {
            if (!difyLastUploadId) {
                wx.showToast({ title: '请先上传照片', icon: 'none' });
                this.setData({ isLoading: false });
                return;
            }
            // 显示确认提示框后调用异步生图任务
            this.showImageTaskConfirmModal(() => {
                this.createImageGenerationTask(query, difyLastUploadId);
            });
            return;
        }
        // 智能对话：支持图片+文字组合
        if (tabType === 0) {
            this.setData({ isLoading: true });
            const { chatUploadId } = this.data;
            if (chatUploadId) {
                // 有图片：使用智能生图的API-key和图片附件
                this.callViaWebSocket({
                    query: query,
                    user: difyUserId,
                        conversation_id: currentConversationId, // 使用确定的会话ID
                        files: [
                            {
                            type: 'image',
                            transfer_method: 'local_file',
                                upload_file_id: chatUploadId
                            }
                        ]
                });
            } else {
                // 无图片：使用智能对话的API-key
                this.callViaWebSocket({
                    query: query,
                    user: difyUserId,
                            conversation_id: currentConversationId // 使用确定的会话ID
                });
            }
        }
     },
     stopPoolingPicTask(){
      utils.showConfirmModal({
        title: '确认关闭',
        content: '关闭后，在[我的]-[会话管理]中重新查看',
        confirmText: '确认',
        cancelText: '取消',
        onConfirm: () => {
          console.log('用户关闭生图任务');
          this.setData({
            generationStatus:'',
            isLoading: false,
            showCustomServiceButton: false
           });
           this.stopTaskPolling();
        },
        onCancel: () => {
          console.log('用户取消关闭任务');
        }
      });
     },
    // 创建异步生图任务
    createImageGenerationTask(query, fileObjectId) {
        console.log('创建异步生图任务:', { query, fileObjectId });
        
        const { difyUserId, currentChatApiKey, oldPictureFileName, customerInfo, isEmployee } = this.data;
        
        // 显示加载状态
        this.setData({ 
            isLoading: true,
            generationStatus: 'generating',
            showCustomServiceButton: false,
            isNewConversation: false // 标记为非新对话
        });
        
        // 准备请求数据
        const requestData = {
            conversationId: this.data.imageConversationId || '',
            conversationFileObjectId: fileObjectId,
            queryWord: query,
            oldPictureFileName: oldPictureFileName
        };
        
        // 如果是员工用户，添加客户信息
        if (isEmployee && customerInfo) {
            requestData.consumerName = customerInfo.name;
            requestData.consumerGender = customerInfo.gender;
            requestData.consumerMobile = customerInfo.mobile;
        }
        
        // 调用后端创建任务接口
        wx.request({
            url: api.base + '/api/InterfaceManageRestService/v1/interfaceManage/createImageTask',
            method: 'POST',
            header: {
              'Content-Type': 'application/x-www-form-urlencoded',
              'X-MiniProgram-Token':wx.getStorageSync('token')
            },
            data: requestData,
            success: (res) => {
                console.log('创建任务响应:', res);
                if (res.data && res.data.code === "0") {
                    const taskId = res.data.data;
                    console.log('任务创建成功，任务ID:', taskId);
                    
                    // 保存任务ID并开始轮询
                    this.setData({ currentTaskId: taskId });
                    
                    // 保存任务ID到本地存储，用于页面切换时恢复
                    wx.setStorageSync('currentTaskId', taskId);
                    
                    this.startTaskPolling(taskId);
                } else {
                    console.error('创建任务失败:', res.data);
                    wx.showToast({ 
                        title: res.data.message || '创建任务失败', 
                        icon: 'none' 
                    });
                    this.setData({ 
                        isLoading: false,
                        generationStatus: ''
                    });
                }
            },
            fail: (error) => {
                console.error('创建任务请求失败:', error);
                wx.showToast({ 
                    title: '网络请求失败', 
                    icon: 'none' 
                });
                this.setData({ 
                    isLoading: false,
                    generationStatus: ''
                });
            }
        });
    },

    // 开始轮询任务状态
    startTaskPolling(taskId) {
        console.log('开始轮询任务状态:', taskId);
        
        if (this.data.isTaskPolling) {
            console.log('已在轮询中，跳过');
            return;
        }
        
        this.setData({ isTaskPolling: true });
        
        // 立即执行一次轮询
        this.pollTaskStatus(taskId);
        
        // 设置定时器，每5秒轮询一次
        this.data.taskPollingTimer = setInterval(() => {
            this.pollTaskStatus(taskId);
        }, 5000);
    },

    // 轮询任务状态
    pollTaskStatus(taskId) {
        console.log('轮询任务状态:', taskId);
        
        wx.request({
            url: api.base + '/api/InterfaceManageRestService/v1/interfaceManage/getTaskStatus',
            method: 'GET',
            header: {
              'Content-Type': 'application/x-www-form-urlencoded',
              'X-MiniProgram-Token':wx.getStorageSync('token')
            },
            data: { taskId: taskId },
            success: (res) => {
                console.log('任务状态响应:', res);
                if (res.data && res.data.code === "0") {
                    const taskData = res.data.data;
                    this.handleTaskStatusUpdate(taskData);
                } else {
                    console.error('获取任务状态失败:', res.data);
                }
            },
            fail: (error) => {
                console.error('轮询任务状态失败:', error);
            }
        });
    },

    // 处理任务状态更新
    handleTaskStatusUpdate(taskData) {
        const { status, newPictureFileName, chatResponseContent, errorMessage } = taskData;
        
        console.log('任务状态更新:', { status, newPictureFileName, errorMessage });
        
        switch (status) {
            case '0': // 待处理
                console.log('任务待处理中...');
                break;
                
            case '1': // 进行中
                console.log('任务处理中...');
                break;
                
            case '2': // 已完成
                console.log('任务完成');
                this.handleTaskCompleted(taskData);
                //刷新用户剩余生图次数
                this.refreshCurrentUserLeftOpportunity();
                break;
            case '3': // 失败
                console.log('任务失败:', errorMessage);
                this.handleTaskFailed(errorMessage);
                //刷新用户剩余生图次数
                this.refreshCurrentUserLeftOpportunity();
                break;
            default:
                console.warn('未知任务状态:', status);
        }
        
    },
    refreshCurrentUserLeftOpportunity(){
      let that = this;
      utils.request(api.getUserInfo, {}, 'POST')
				.then(function(res){
					wx.hideLoading();
					if (res.code == "0") {
						const info = res.data || {};
						that.setData({
              leftOpportunity:info.gen_pic_opportunity
            });
					} else {
						wx.showToast({ title: res.message || '获取用户信息失败', icon: 'none' });
					}
				})
				.catch(function(e){
					wx.hideLoading();
					wx.showToast({ title: e || '网络异常', icon: 'none' });
				});
    },
    // 处理任务完成
    handleTaskCompleted(taskData) {
        const { newPictureFileName, chatResponseContent, conversationId } = taskData;
        
        console.log('任务完成，更新UI:', { newPictureFileName, conversationId });
        
        // 停止轮询
        this.stopTaskPolling();
        
        // 清理本地存储的任务ID
        wx.removeStorageSync('currentTaskId');
        
        // 更新会话ID
        if (conversationId) {
            this.setData({ imageConversationId: conversationId });
        }
        
        // 更新生成图片
        if (newPictureFileName) {
            this.setData({ 
                newPictureFileName: newPictureFileName,
                afterImages: [newPictureFileName]
            });
        }
        
        // 显示AI响应内容
        if (chatResponseContent) {
            let result = app.towxml(chatResponseContent,'markdown',{
              // theme:'dark',
              events:{
                tap:e => {
                  console.log('tap',e);
                },
                change:e => {
                  console.log('todo',e);
                }
              }
            });
            this.setData({ 
                aiResponseContent: result,
                aiResponseContentRaw: chatResponseContent // 保存原始内容用于复制
            });
        }
        
        // 更新状态
        this.setData({
            isLoading: false,
            generationStatus: 'done',
            showCustomServiceButton: true
        });
        
        console.log('生图任务完成，图片已更新，AI响应内容已显示');
    },

    // 处理任务失败
    handleTaskFailed(errorMessage) {
        console.log('任务失败:', errorMessage);
        
        // 停止轮询
        this.stopTaskPolling();
        
        // 显示错误信息
        wx.showToast({ 
            title: errorMessage || '生图失败', 
            icon: 'none',
            duration: 3000
        });
        
        // 重置状态
        this.setData({
            isLoading: false,
            generationStatus: '',
            showCustomServiceButton: false
        });
    },

    // 停止任务轮询
    stopTaskPolling() {
        console.log('停止任务轮询');
        
        if (this.data.taskPollingTimer) {
            clearInterval(this.data.taskPollingTimer);
            this.data.taskPollingTimer = null;
        }
        
        this.setData({ 
            isTaskPolling: false,
            currentTaskId: ''
        });
     },

    // WebSocket 相关：建立连接（若未连接）
    ensureWebSocketConnected() {
        // 每次连接前都重置消息绑定状态，确保重新绑定
        this._wsMessageBound = false;
        
        if (this.ws && this.ws.readyState === 1) {
            // 如果连接已存在，直接返回
            return Promise.resolve();
        }
        return new Promise((resolve, reject) => {
          try {
            const url = api.dify.wsProxy;
            console.log('Connecting to WebSocket:', url);
            const socketTask = wx.connectSocket({ url });
            this.ws = socketTask;
            socketTask.onOpen(() => {
              console.log('WebSocket connected');
        // 绑定消息监听器（只绑定一次）
          if (!this._wsMessageBound) {
            this._wsMessageBound = true;
            console.log('WebSocket消息监听器已绑定');
            this.ws.onMessage((evt) => {
              try {
                console.log('收到WebSocket消息:', evt.data);
                const data = JSON.parse(evt.data || '{}');
                console.log('解析后的WebSocket消息:', data);
                
                // 通用事件：会话ID、message_id
                if (data.event === 'conversation_id' && data.conversation_id) {
                  // 使用流上下文中的isImageTab，而不是当前tab状态
                  const ctx = this._streamCtx;
                  const isImageTab = ctx ? ctx.isImageTab : (this.data.activeTab === 1);
                  // console.log('Processing conversation_id for', isImageTab ? 'image' : 'dialog', 'tab');
                  if (isImageTab) {
                    // 智能生图会话ID
                    if (!this.data.imageConversationId) {
                      this.setData({ imageConversationId: data.conversation_id });
                    }
                  } else {
                    // 智能对话会话ID
                    if (!this.data.conversationId) {
                      this.setData({ conversationId: data.conversation_id });
                    }
                  }
                  this.saveConversationIdToCache(data.conversation_id);
                }
                if (data.event === 'message_id' && data.message_id) {
                  this.lastMessageId = data.message_id;
                }

                // 基于当前流上下文更新UI，防止旧监听拼接到历史消息
                const ctx = this._streamCtx;
                if (!ctx) {
                  console.log('No stream context available, ignoring message:', data);
                  return;
                }
                // console.log('Processing message with context:', ctx, 'data:', data);
                
                // 处理流式响应数据
                if (data.event === 'chunk' && data.chunk) {
                  // 开始接收流式响应，将用户消息插入到AI消息之前
                  if (!ctx.isImageTab && this._pendingUserMessage) {
                    // 将用户消息插入到AI消息占位符之前
                    const currentList = [...this.data.chatList];
                    currentList.splice(ctx.startIndex, 0, this._pendingUserMessage);
                    this.setData({ chatList: currentList });
                    this.saveChatListToCache();
                    this.scrollToBottom();
                    this._pendingUserMessage = null; // 清空暂存消息
                    // 更新AI消息的索引位置
                    ctx.startIndex += 1;
                    console.log('用户消息已插入到AI消息之前，AI消息新索引:', ctx.startIndex);
                  }
                  
                  ctx.assembled += data.chunk;
                  // console.log('Processing chunk for', ctx.isImageTab ? 'image' : 'dialog', 'tab, content:', ctx.assembled);
                  this.updateChatMessage(ctx);
                } else if (data.event === 'message' && data.answer) {
                  // 处理Dify返回的message事件（直接完整消息）
                  // 开始接收响应，将用户消息插入到AI消息之前
                  if (!ctx.isImageTab && this._pendingUserMessage) {
                    // 将用户消息插入到AI消息占位符之前
                    const currentList = [...this.data.chatList];
                    currentList.splice(ctx.startIndex, 0, this._pendingUserMessage);
                    this.setData({ chatList: currentList });
                    this.saveChatListToCache();
                    this.scrollToBottom();
                    this._pendingUserMessage = null; // 清空暂存消息
                    // 更新AI消息的索引位置
                    ctx.startIndex += 1;
                    console.log('用户消息已插入到AI消息之前，AI消息新索引:', ctx.startIndex);
                  }
                  
                  ctx.assembled = data.answer; // 直接设置，不累加
                  console.log('Processing message for', ctx.isImageTab ? 'image' : 'dialog', 'tab, content:', ctx.assembled);
                  this.updateChatMessage(ctx);
                }
                
                // 检查是否有HTTP错误状态码
                if (data.status && data.status !== 200) {
                  const errorMessage = data.message || data.error || `请求失败 (状态码: ${data.status})`;
                  wx.showToast({ 
                    title: errorMessage, 
                    icon: 'none',
                    duration: 3000
                  });
                  this.setData({ isLoading: false });
                  
                  // 清空暂存的用户消息，因为HTTP状态码错误
                  if (this._pendingUserMessage) {
                    console.log('HTTP状态码错误，清空暂存的用户消息');
                    this._pendingUserMessage = null;
                  }
                  
                  // 移除AI消息占位符，因为HTTP状态码错误
                  if (!ctx.isImageTab && ctx.startIndex >= 0) {
                    const currentList = [...this.data.chatList];
                    if (currentList.length > ctx.startIndex && currentList[ctx.startIndex].type === 'ai' && !currentList[ctx.startIndex].content) {
                      currentList.splice(ctx.startIndex, 1);
                      this.setData({ chatList: currentList });
                      this.saveChatListToCache();
                      console.log('HTTP状态码错误，已移除AI消息占位符');
                    }
                  }
                  
                  this.closeWebSocketConnection();
                  return;
                }
                if (data.event === 'end' && data.end) {
                  this.setData({ isLoading: false });
                  
                  // 对AI咨询模块的响应完成内容进行towxml渲染
                  if (!ctx.isImageTab) {
                    try {
                      const list = [...this.data.chatList];
                      const idx = ctx.startIndex;
                      if (idx >= 0 && idx < list.length && list[idx].type === 'ai') {
                        // 仅在最终完成后渲染，避免流式过程中频繁解析
                        const result = app.towxml(list[idx].content, 'markdown', {
                          events: {
                            tap: e => {
                              console.log('towxml tap', e);
                            },
                            change: e => {
                              console.log('towxml change', e);
                            }
                          }
                        });
                        list[idx] = Object.assign({}, list[idx], { towxmlNodes: result });
                        this.setData({ chatList: list });
                        console.log('AI咨询响应完成，已进行towxml渲染');
                      }
                    } catch (e) {
                      console.warn('AI咨询towxml渲染失败', e);
                    }
                  }
                  
                  this.saveChatListToCache();
                  if (!ctx.isImageTab && this.lastMessageId) {
                    this.fetchSuggestedQuestions(this.lastMessageId, this.data.difyUserId);
                  }
                  // 智能生图：如果流式响应结束但没有找到图片，重置状态
                  if (ctx.isImageTab && this.data.generationStatus === 'generating') {
                    console.log('智能生图流式响应结束，但未找到图片，重置状态');
                    this.setData({ generationStatus: '' });
                  }
                  // 关闭当前流上下文，避免后续误拼接
                  this._streamCtx = null;
                  console.log('Stream ended, loading state reset to false');
                }
                if (data.event === 'error') {
                  // 显示错误信息
                  const errorMessage = data.message || data.error || '生成失败';
                  wx.showToast({ 
                    title: errorMessage, 
                    icon: 'none',
                    duration: 3000
                  });
                  this.setData({ isLoading: false });
                  
                  // 清空暂存的用户消息，因为WebSocket返回了错误
                  if (this._pendingUserMessage) {
                    console.log('WebSocket返回错误，清空暂存的用户消息');
                    this._pendingUserMessage = null;
                  }
                  
                  // 移除AI消息占位符，因为WebSocket返回了错误
                  if (!ctx.isImageTab && ctx.startIndex >= 0) {
                    const currentList = [...this.data.chatList];
                    if (currentList.length > ctx.startIndex && currentList[ctx.startIndex].type === 'ai' && !currentList[ctx.startIndex].content) {
                      currentList.splice(ctx.startIndex, 1);
                      this.setData({ chatList: currentList });
                      this.saveChatListToCache();
                      console.log('WebSocket返回错误，已移除AI消息占位符');
                    }
                  }
                  
                  // 关闭WebSocket连接
                  this.closeWebSocketConnection();
                }
              } catch (e) {
                console.error('Failed to parse WebSocket message:', e);
              }
            });
          }
                  resolve();
              });
              socketTask.onError((e) => {
                  console.error('WebSocket connection error:', e);
                  // 显示连接错误提示
                  wx.showToast({ 
                      title: 'WebSocket连接失败', 
                      icon: 'none',
                      duration: 3000
                  });
                  this.setData({ isLoading: false });
                  reject(e);
              });
              
              socketTask.onClose((e) => {
                  console.log('WebSocket connection closed:', e);
                  
                  // 检查是否有正在进行的操作
                  const isGenerating = this.data.generationStatus === 'generating';
                  const isLoading = this.data.isLoading;
                  
                  if (isGenerating || isLoading) {
                      console.log('WebSocket断开时检测到正在进行的操作，尝试自动重连');
                      // 延迟重连，避免频繁重连
                      setTimeout(() => {
                          this.reconnectWebSocketForOngoingOperation();
                      }, 1000);
                  } else {
                      // 没有正在进行的操作，正常关闭
                      this.setData({ isLoading: false });
                  }
              });
          } catch (e) {
              console.error('WebSocket connection exception:', e);
              reject(e);
          }
        });
    },

    // 通过 WebSocket 调用代理并处理流式分片
    callViaWebSocket(payload) {
        this.ensureWebSocketConnected().then(() => {
				const now = this.formatDateTime(new Date());
        const isImageTab = this.data.activeTab === 1;
				
				console.log('callViaWebSocket - isImageTab:', isImageTab, 'activeTab:', this.data.activeTab);
				
				// 智能生图：不添加AI消息占位，只处理图片
        if (isImageTab) {
            console.log('智能生图模式：不显示聊天内容，只处理图片');
            // 智能生图不需要聊天记录，直接设置流上下文用于图片处理
            this._streamCtx = { isImageTab, startIndex: -1, now, assembled: '' };
        } else {
            // 智能对话：添加AI消息占位
            console.log('Adding AI placeholder to chatList, current length:', this.data.chatList.length);
            const newChatList = [...this.data.chatList, { type: 'ai', content: '', time: now }];
            this.setData({ chatList: newChatList });
            const startIndex = newChatList.length - 1;
            this._streamCtx = { isImageTab, startIndex, now, assembled: '' };
            console.log('AI placeholder added at index:', startIndex, 'new chatList length:', newChatList.length);
        }
        
        console.log('Created new stream context:', this._streamCtx);

        const message = {
            action: 'chat',
            payload: payload,
            authorization: 'Bearer ' + (api.dify && api.dify.apiKey ? api.dify.apiKey : '')
        };
        console.log('Sending WebSocket message:', message);
        this.ws.send({ data: JSON.stringify(message) });
      })
      .catch((error) => {
          console.error('WebSocket connection failed:', error);
          wx.showToast({ title: '连接失败', icon: 'none' });
          this.setData({ isLoading: false });
      });
    },
    /**
     * 开启新对话
     */
    startNewChat() {
      let that = this;
      this.isLogin(function (){
        that.checkInfomationAndInitRole();
        // 使用通用确认框
        const modal = utils.showConfirmModal({
          title: '确认清空',
          content: '确定要开启新对话吗？当前对话内容将被清空。',
          confirmText: '确定',
          cancelText: '取消',
          onConfirm: () => {
              const isImageTab = that.data.activeTab === 1;
              if (isImageTab) {
                  // 智能生图：清空图片和会话ID
                  const updateData = { 
                      beforeImages: ['/static/images/default_Picture.jpg'], 
                      afterImages: ['/static/images/default_Picture.jpg'], 
                      inputValue: '', 
                      imageConversationId: '',
                      showCustomServiceButton: false, // 隐藏联系客服按钮
                      difyLastUploadId: '',
                      difyLastLocalPath: '',
                      generationStatus: '',
                      // 清空生图记录相关状态
                      oldPictureFileName: '',
                      newPictureFileName: '',
                      currentQueryWord: '',
                      currentChatApiKey: '',
                      conversationFileObjectId: '',
                      // 清空智能生图历史记录相关状态
                      historyOldPictureFileName: '',
                      historyNewPictureFileName: '',
                      historyConversationFileObjectId: '',
                      // 清空异步任务相关状态
                      currentTaskId: '',
                      isTaskPolling: false, 
                      aiResponseContent:'',
                      aiResponseContentRaw:'' // 同时清空原始内容
                  };
                  
                  // 如果是从历史页面跳转过来的，清空历史会话相关状态
                  if (that.data.fromHistory) {
                      updateData.fromHistory = false;
                      updateData.historyConversationId = '';
                      updateData.historyName = '';
                      updateData.historyLoaded = false;
                      updateData.historyType = '';
                  }
                  
                  // 设置新对话标识
                  updateData.isNewConversation = true;
                  
                  that.setData(updateData);
                  // 停止任务轮询
                  that.stopTaskPolling();
                  try { 
                      wx.setStorageSync(that.getStorageKey('image_conversation_id'), '');
                  } catch (_) {}
                  
                  // 员工用户开启新对话时，直接显示客户信息输入
                  if (that.data.isEmployee) {
                    that.showCustomerInfoModal();
                  }
              } else {
                  // 智能对话：清空聊天记录
                  const updateData = { 
                      chatList: [],
                      inputValue: '',
                      conversationId: ''
                  };
                  
                  // 如果是从历史页面跳转过来的，清空历史会话相关状态
                  if (that.data.fromHistory) {
                      updateData.fromHistory = false;
                      updateData.historyConversationId = '';
                      updateData.historyName = '';
                      updateData.historyLoaded = false;
                  }
                  
                  // 设置新对话标识
                  updateData.isNewConversation = true;
                  
                  that.setData(updateData);
                  try {
                      wx.setStorageSync(that.getStorageKey('dialog_list'), []);
                      wx.setStorageSync(that.getStorageKey('dialog_conversation_id'), '');
                  } catch (_) {}
              }
                  wx.showToast({
                      title: '已开启新对话',
                      icon: 'success'
                  });
          },
          onCancel: () => {
              console.log('用户取消了开启新对话');
          }
      });
      });
        
    },

    /**
     * 切换猜你想问显示状态
     */
    toggleSuggestions() {
        this.setData({
            isSuggestionsVisible: !this.data.isSuggestionsVisible
        });
    },


    /**
     * 选择建议问题
     */
    selectSuggestion(e) {
      let that = this;
      this.isLogin(function (){
        that.checkInfomationAndInitRole();
        const { suggestion } = e.currentTarget.dataset;
          // 直接发送消息，不放入输入框
          that.sendSuggestionMessage(suggestion);
          // 收起猜你想问区域
          that.setData({
              isSuggestionsVisible: false
          });
      });
        
    },

    /**
     * 发送建议问题消息（直接发送到大模型）
     */
    sendSuggestionMessage(suggestion) {
        const now = this.formatDateTime(new Date());
        const isImageTab = this.data.activeTab === 1;
        const { isEmployee } = this.data;
        
        if (isImageTab) {
            // 智能生图：检查是否已上传图片
            if (!this.data.difyLastUploadId) {
                wx.showToast({ 
                    title: '请先上传照片', 
                    icon: 'none' 
                });
                return;
            }
            
            // 员工用户需要检查客户信息
            if (isEmployee) {
                const { cachedCustomerInfo } = this.data;
                
                if (cachedCustomerInfo) {
                    // 有缓存的客户信息，直接复用
                    console.log('复用缓存的客户信息:', cachedCustomerInfo);
                    this.setData({ customerInfo: cachedCustomerInfo });
                } else {
                    // 没有缓存信息，需要输入客户信息
                    this.setData({ pendingMessage: suggestion });
                    this.showCustomerInfoModal();
                    return;
                }
            }
            
            // 智能生图：设置当前查询词和API Key，准备新的生图
            this.setData({
                currentQueryWord: suggestion,
                currentChatApiKey: api.dify && api.dify.apiKey ? api.dify.apiKey : ''
            });
            
            // 智能生图：不显示用户消息，直接发送
            console.log('智能生图提示词发送:', suggestion);
            this.callDifyChat(suggestion, 1);
        } else {
            // 智能对话：添加用户消息到聊天列表
            const userMessage = { type: 'user', content: suggestion, time: now };
            const list = [...this.data.chatList, userMessage];
            this.setData({ chatList: list });
            this.saveChatListToCache();
            this.scrollToBottom();
            this.callDifyChat(suggestion, 0);
        }
    },

    /**
     * 选择图片美化提示词
     */
    selectImagePrompt(e) {
      let that = this;
      this.isLogin(function (){
        that.checkInfomationAndInitRole();
        const { prompt } = e.currentTarget.dataset;
        const { imagePromptObjects } = that.data;
        
        // 根据显示的promptWord找到对应的完整对象，获取promptDetail
        const promptObject = imagePromptObjects.find(obj => obj.promptWord === prompt);
        const promptToSend = promptObject && promptObject.promptDetail ? promptObject.promptDetail : prompt;
        
        console.log('选择的提示词:', prompt);
        console.log('发送的提示词详情:', promptToSend);
        
        // 直接发送消息，使用promptDetail
        that.sendSuggestionMessage(promptToSend);
      });
        
    },

    /**
     * 刷新智能效果模拟提示词
     */
    refreshImagePrompts() {
        console.log('刷新智能效果模拟提示词');
        
        
        // 调用后端接口获取新的提示词
        wx.request({
            url: api.searchUserPicChatPrompt,
            method: 'POST',
            header: {
                'Content-Type': 'application/json',
                'X-MiniProgram-Token':wx.getStorageSync('token')
            },
            success: (res) => {
                wx.hideLoading();
                console.log('获取提示词响应:', res);
                
                if (res.statusCode === 200 && res.data && res.data.code === '0') {
                    const promptObjects = res.data.data || [];
                    if (promptObjects.length > 0) {
                        // 保存完整的提示词对象
                        this.setData({
                            imagePromptObjects: promptObjects
                        });
                        
                        // 提取对象中的promptWord属性作为显示用的提示词
                        const newPrompts = promptObjects.map(item => item.promptWord || item).filter(prompt => prompt);
                        
                        if (newPrompts.length > 0) {
                            // 更新显示用的提示词列表
                            this.setData({
                                imagePrompts: newPrompts
                            });
                            
                            console.log('提示词更新成功:', newPrompts);
                            console.log('完整提示词对象:', promptObjects);
                        } else {
                            console.log('提示词数据格式错误:', newPrompts);
                        }
                    } else {
                        wx.showToast({
                            title: '暂无新提示词',
                            icon: 'none',
                            duration: 1500
                        });
                    }
                } else {
                    console.error('获取提示词失败:', res.data);
                    wx.showToast({
                        title: res.data.message || '操作失败',
                        icon: 'none',
                        duration: 2000
                    });
                }
            },
            fail: (err) => {
                wx.hideLoading();
                console.error('获取提示词请求失败:', err);
                wx.showToast({
                    title: '网络请求失败',
                    icon: 'none',
                    duration: 2000
                });
            }
        });
    },

    /**
     * 上传照片
     */
    // 显示上传方式选择遮罩层
    showUploadModal() {
      let that = this;
      this.isLogin(function (){
        that.checkInfomationAndInitRole();
        // 检查是否正在上传
        if (that.data.isUploadingImage) {
          wx.showToast({
              title: '图片上传中，请稍候...',
              icon: 'none'
          });
          return;
        }
        that.setData({ showUploadModal: true });
      });
        
    },
    onContact(){
      this.setData({
        sw:true
      });
    },
    // 隐藏上传方式选择遮罩层
    hideUploadModal() {
        this.setData({ showUploadModal: false });
    },

    // 显示智能对话上传方式选择遮罩层
    showChatUploadModal() {
      let that = this;
      this.isLogin(function (){
        that.checkInfomationAndInitRole();
        // 检查是否正在上传
        if (that.data.isUploadingChatImage) {
          wx.showToast({
              title: '图片上传中，请稍候...',
              icon: 'none'
          });
          return;
        }
        that.setData({ showChatUploadModal: true });
      });
        
    },

    // 隐藏智能对话上传方式选择遮罩层
    hideChatUploadModal() {
        this.setData({ showChatUploadModal: false });
    },

    // 智能对话拍照上传
    takeChatPhoto() {
        this.setData({ showChatUploadModal: false,sw:true });
        wx.chooseImage({
            count: 1,
            sizeType: ['compressed'],
            sourceType: ['camera'],
            success: (res) => {
                const tempFilePath = res.tempFilePaths[0];
                this.setData({ chatUploadLocalPath: tempFilePath });
                this.uploadChatImage(tempFilePath);
            },
            fail: () => {
                wx.showToast({ title: '拍照失败', icon: 'none' });
            }
        });
    },

    // 智能对话相册上传
    selectChatFromAlbum() {
        this.setData({ showChatUploadModal: false,sw:true });
        wx.chooseImage({
            count: 1,
            sizeType: ['compressed'],
            sourceType: ['album'],
            success: (res) => {
                const tempFilePath = res.tempFilePaths[0];
                this.setData({ chatUploadLocalPath: tempFilePath });
                this.uploadChatImage(tempFilePath);
            },
            fail: () => {
                wx.showToast({ title: '取消选择图片', icon: 'none' });
            }
        });
    },

    // 智能对话图片上传到服务器
    uploadChatImage(filePath) {
        // 设置上传状态
        this.setData({ isUploadingChatImage: true });
        
        const uploadUrl = api.dify.fileUpload;
        const header = {
            'Authorization': 'Bearer ' + (api.dify && api.dify.apiKey ? api.dify.apiKey : '')
        };
        wx.uploadFile({
            url: uploadUrl,
            filePath: filePath,
            name: 'file',
            header: header,
            formData: { user: this.data.difyUserId },
            success: (uploadRes) => {
                try {
                    const data = JSON.parse(uploadRes.data || '{}');
                    if (data && data.id) {
                        this.setData({ 
                            chatUploadId: data.id,
                            showPreSendImage: true,
                            preSendImagePath: filePath,
                            isUploadingChatImage: false // 上传完成
                        });
                        wx.showToast({ title: '图片上传成功', icon: 'success' });
                    } else {
                        this.setData({ isUploadingChatImage: false }); // 上传失败
                        wx.showToast({ title: '上传失败', icon: 'none' });
                    }
                } catch (e) {
                    this.setData({ isUploadingChatImage: false }); // 解析失败
                    wx.showToast({ title: '上传解析失败', icon: 'none' });
                }
            },
            fail: () => {
                this.setData({ isUploadingChatImage: false }); // 上传失败
                wx.showToast({ title: '上传失败', icon: 'none' });
            }
        });
    },

    // 拍照上传
    takePhoto() {
        this.setData({ showUploadModal: false,sw:true });
        wx.chooseImage({
            count: 1,
            sizeType: ['compressed'],
            sourceType: ['camera'],
            success: (res) => {
                const tempFilePath = res.tempFilePaths[0];
                // 先在前端预览原图
                this.setData({
                    beforeImages: [tempFilePath],
                    difyLastLocalPath: tempFilePath
                });
                
                // 先调用uploadFile接口上传到后台服务器
                this.uploadToBackend(tempFilePath);
            },
            fail: () => {
                wx.showToast({ title: '拍照失败', icon: 'none' });
            }
        });
    },

    // 相册上传
    selectFromAlbum() {
        this.setData({ showUploadModal: false,sw:true });
        wx.chooseImage({
            count: 1,
            sizeType: ['compressed'],
            sourceType: ['album'],
            success: (res) => {
                const tempFilePath = res.tempFilePaths[0];
                // 先在前端预览原图
                this.setData({
                    beforeImages: [tempFilePath],
                    difyLastLocalPath: tempFilePath
                });
                
                // 先调用uploadImage接口上传到后台服务器
                this.uploadToBackend(tempFilePath);
            },
            fail: () => {
                wx.showToast({ title: '取消选择图片', icon: 'none' });
            }
        });
    },

    // 上传图片到后台服务器获取oldPictureFileName
    uploadToBackend(filePath) {
        // 设置上传状态
        this.setData({ isUploadingImage: true });
        wx.showLoading({ title: '上传图片中...' });
        
        // 调用uploadFile接口上传到后台服务器
        wx.uploadFile({
            url: api.uploadFile, // 假设API基础路径
            filePath: filePath,
            name: 'upfile',
            success: (res) => {
                try {
                    const data = JSON.parse(res.data || '{}');
                    if (data && data.relaName) {
                        // 保存oldPictureFileName
                        this.setData({ oldPictureFileName: data.relaName });
                        console.log('后台上传成功，文件名:', data.relaName);
                        
                        // 然后上传到dify
                        this.uploadToDify(filePath);
                    } else {
                        this.setData({ isUploadingImage: false }); // 上传失败
                        wx.hideLoading();
                        wx.showToast({ title: '后台上传失败', icon: 'none' });
                    }
                } catch (e) {
                    this.setData({ isUploadingImage: false }); // 解析失败
                    wx.hideLoading();
                    console.error('解析后台上传响应失败:', e);
                    wx.showToast({ title: '上传解析失败', icon: 'none' });
                }
            },
            fail: (err) => {
                this.setData({ isUploadingImage: false }); // 上传失败
                wx.hideLoading();
                console.error('后台上传失败:', err);
                wx.showToast({ title: '后台上传失败', icon: 'none' });
            }
        });
    },

    // 上传图片到dify
    uploadToDify(filePath) {
        const uploadUrl = api.dify.fileUpload;
        const header = {
            'Authorization': 'Bearer ' + (api.dify && api.dify.apiKey ? api.dify.apiKey : '')
        };
        wx.uploadFile({
            url: uploadUrl,
            filePath: filePath,
            name: 'file',
            header: header,
            formData: { user: this.data.difyUserId },
            success: (uploadRes) => {
                this.setData({ isUploadingImage: false }); // 上传完成
                wx.hideLoading();
                try {
                    const data = JSON.parse(uploadRes.data || '{}');
                    if (data && data.id) {
                        this.setData({ difyLastUploadId: data.id });
                        wx.showToast({ title: '上传成功', icon: 'success' });
                    } else {
                        wx.showToast({ title: 'Dify上传失败', icon: 'none' });
                    }
                } catch (e) {
                    wx.showToast({ title: 'Dify上传解析失败', icon: 'none' });
                }
            },
            fail: () => {
                this.setData({ isUploadingImage: false }); // 上传失败
                wx.hideLoading();
                wx.showToast({ title: 'Dify上传失败', icon: 'none' });
            }
        });
    },

    // 原有的上传照片方法（保留作为备用）
    uploadPhoto() {
        wx.chooseImage({
            count: 1,
            sizeType: ['compressed'],
            sourceType: ['album', 'camera'],
            success: (res) => {
                const tempFilePath = res.tempFilePaths[0];
                // 先在前端预览原图
                this.setData({
                    beforeImages: [tempFilePath],
                    difyLastLocalPath: tempFilePath
                });
                const uploadUrl = api.dify.fileUpload;
                const header = {
                    'Authorization': 'Bearer ' + (api.dify && api.dify.apiKey ? api.dify.apiKey : '')
                };
                wx.uploadFile({
                    url: uploadUrl,
                    filePath: tempFilePath,
                    name: 'file',
                    header: header,
                    formData: { user: this.data.difyUserId },
                    success: (uploadRes) => {
                        try {
                            const data = JSON.parse(uploadRes.data || '{}');
                            if (data && data.id) {
                                this.setData({ difyLastUploadId: data.id });
                                wx.showToast({ title: '上传成功', icon: 'success' });
                            } else {
                                wx.showToast({ title: '上传失败', icon: 'none' });
                            }
                        } catch (e) {
                            wx.showToast({ title: '上传解析失败', icon: 'none' });
                        }
                    },
                    fail: () => {
                        wx.showToast({ title: '上传失败', icon: 'none' });
                    }
                });
            },
            fail: () => {
                wx.showToast({ title: '取消选择图片', icon: 'none' });
            }
        });
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    // 移除重复的onHide方法，使用上面的onHide方法

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {
        this.closeWebSocketIfNeeded();
        this.stopTaskPolling();
    },

    closeWebSocketIfNeeded() {
        try {
            if (this.ws) {
                this.ws.close();
                this.ws = null;
            }
        } catch (_) {}
    },

    // 关闭WebSocket连接（用于错误处理）
    closeWebSocketConnection() {
        try {
            console.log('Closing WebSocket connection due to error...');
            if (this.ws) {
                this.ws.close();
                this.ws = null;
                this._wsMessageBound = false;
            }
            // 清理流上下文
            this._streamCtx = null;
            console.log('WebSocket connection closed');
        } catch (e) {
            console.error('Error closing WebSocket connection:', e);
        }
    },

	// 获取 Dify 建议问题
	fetchSuggestedQuestions(messageId, userId) {
		try {
			const url = (api.dify && api.dify.suggested ? api.dify.suggested : '') + messageId + '/suggested';
			const header = {
				'Authorization': 'Bearer ' + (api.dify && api.dify.dialogApiKey ? api.dify.dialogApiKey : (api.dify.apiKey || ''))
			};
			const params = `?user=${encodeURIComponent(userId || this.data.difyUserId)}`;
			wx.request({
				url: url + params,
				method: 'GET',
				header: header,
				success: (res) => {
					try {
						if (res.statusCode === 200 && res.data && res.data.result === 'success' && Array.isArray(res.data.data)) {
							this.setData({ suggestions: res.data.data.slice(0, 3), isSuggestionsVisible: true,showSuggestions:true });
						} else {
							console.warn('Suggested API unexpected response', res);
						}
					} catch (e) {
						console.warn('parse suggested response failed', e);
					}
				},
				fail: (err) => {
					console.warn('fetchSuggestedQuestions failed', err);
				}
			});
		} catch (e) {
			console.warn('fetchSuggestedQuestions exception', e);
		}
	},

	// 从大模型响应中提取图片URL（智能生图功能）
	extractImageUrlFromResponse(responseText) {
		try {
			console.log('extractImageUrlFromResponse called with:', responseText);
			
			// 更精确的图片URL匹配模式
			const imageUrlPatterns = [
				// 标准HTTP/HTTPS图片URL
				/https?:\/\/[^\s"'<>]+\.(jpg|jpeg|png|gif|webp|bmp)(\?[^\s"'<>]*)?/gi,
				// 带参数的图片URL
				/https?:\/\/[^\s"'<>]+\.(jpg|jpeg|png|gif|webp|bmp)\?[^\s"'<>]*/gi,
				// 简单图片URL
				/https?:\/\/[^\s"'<>]+\.(jpg|jpeg|png|gif|webp|bmp)/gi
			];
			
			let foundImageUrl = null;
			
			// 尝试不同的匹配模式
			for (const pattern of imageUrlPatterns) {
				const matches = responseText.match(pattern);
				if (matches && matches.length > 0) {
					// 取第一个匹配的图片URL，并清理可能的引号
					foundImageUrl = matches[0].replace(/^["']|["']$/g, '');
					console.log('Found image URL with pattern:', pattern, 'URL:', foundImageUrl);
					break;
				}
			}
			
			// 如果找到图片URL，更新afterImages数组
			if (foundImageUrl && !this.data.afterImages.includes(foundImageUrl)) {
				console.log('Found image URL:', foundImageUrl);
				
				// 保存newPictureFileName
				this.setData({
					newPictureFileName: foundImageUrl,
					afterImages: [foundImageUrl] // 替换为新的图片URL
				});
				
				// 显示生成完成状态
				this.setData({
					generationStatus: 'done'
				});
				
				// 显示生成完成提示
				wx.showToast({
					title: '生成完成',
					icon: 'success',
					duration: 2000
				});
				
				// 显示联系客服定制方案按钮
				console.log('显示联系客服定制方案按钮');
				this.setData({
					showCustomServiceButton: true
				});
				console.log('联系客服按钮状态已设置为true');
				
				// 调用addPicChat接口生成生图记录
				this.addPicChatRecord();
				
				// 3秒后隐藏状态提示
				setTimeout(() => {
					this.setData({
						generationStatus: ''
					});
				}, 3000);
			}
		} catch (e) {
			console.warn('extractImageUrlFromResponse failed:', e);
		}
	},

	// 调用addPicChat接口生成生图记录
	addPicChatRecord() {
		const { oldPictureFileName, newPictureFileName, currentQueryWord, currentChatApiKey, imageConversationId, conversationFileObjectId } = this.data;
		
		// 检查必要参数
		if (!oldPictureFileName || !newPictureFileName) {
			console.warn('生图记录参数不完整:', { oldPictureFileName, newPictureFileName });
			return;
		}
		
		// 生成32位UUID
		const id = this.generateUUID();
		
		// 准备请求参数
		const params = {
			id: id,
			oldPictureFileName: oldPictureFileName,
			newPictureFileName: newPictureFileName,
			queryWord: currentQueryWord || '',
			chatFinishTime: new Date().toISOString(),
			conversationId: imageConversationId || '', // 智能生图会话ID
			conversationFileObjectId: conversationFileObjectId || '' // 智能生图会话中的文件对象ID
		};
		
		console.log('调用addPicChat接口，参数:', params);
		
		// 调用addPicChat接口
		utils.request(api.addPicChat, params, 'POST')
			.then((res) => {
				if (res.code === "0") {
					console.log('生图记录保存成功');
				} else {
					console.warn('生图记录保存失败:', res.message);
				}
			})
			.catch((err) => {
				console.error('调用addPicChat接口失败:', err);
			});
	},

	// 生成32位UUID
	generateUUID() {
		return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
			const r = Math.random() * 16 | 0;
			const v = c === 'x' ? r : (r & 0x3 | 0x8);
			return v.toString(16);
		});
	},

	// 预览处理前图片
	previewBeforeImage(e) {
		const src = e.currentTarget.dataset.src;
		if (src && this.data.beforeImages.length > 0) {
			wx.previewImage({
				current: src,
				urls: this.data.beforeImages,
				fail: (err) => {
					console.error('预览图片失败:', err);
					wx.showToast({
						title: '预览失败',
						icon: 'none'
					});
				}
			});
    }
    this.setData(
      {
        sw:true
      }
    );
	},

	// 预览处理后图片
	previewAfterImage(e) {
		const src = e.currentTarget.dataset.src;
		if (src && this.data.afterImages.length > 0) {
			wx.previewImage({
				current: src,
				urls: this.data.afterImages,
				fail: (err) => {
					console.error('预览图片失败:', err);
					wx.showToast({
						title: '预览失败',
						icon: 'none'
					});
				}
			});
    }
    this.setData(
      {
        sw:true
      }
    );
	},

	// 更新聊天消息（统一处理智能对话和智能生图）
	updateChatMessage(ctx) {
		// console.log('updateChatMessage called with ctx:', ctx);
		
		if (ctx.isImageTab) {
			// 智能生图：不更新聊天列表，只处理图片URL提取
			console.log('智能生图模式：处理图片URL提取，内容:', ctx.assembled);
			this.extractImageUrlFromResponse(ctx.assembled);
		} else {
			// 智能对话：处理思考过程和正常响应
			this.processAIResponse(ctx);
		}
	},

	// 处理AI响应，识别思考过程
	processAIResponse(ctx) {
		const currentList = [...this.data.chatList];
		let processedContent = ctx.assembled;
		let displayContent = processedContent;
		
		// 检查是否包含思考标签
		const thinkStartIndex = processedContent.indexOf('<think>');
		const thinkEndIndex = processedContent.indexOf('</think>');
		
		if (thinkStartIndex !== -1 && thinkEndIndex === -1) {
			// 开始思考，但还没结束
			if (!this.data.isThinking) {
				console.log('AI开始思考...');
				this.setData({
					isThinking: true,
					thinkingStartTime: Date.now(),
					thinkingContent: ''
				});
			}
			
			// 提取思考内容
			const thinkingContent = processedContent.substring(thinkStartIndex + 7); // 7是'<think>'的长度
			this.setData({ thinkingContent: thinkingContent });
			
			// 显示思考状态
			displayContent = '🤔 AI正在思考中...\n\n' + thinkingContent;
			
		} else if (thinkStartIndex !== -1 && thinkEndIndex !== -1) {
			// 思考过程完成（一次性收到完整内容）
			const thinkingDuration = this.data.isThinking ? 
				Math.round((Date.now() - this.data.thinkingStartTime) / 1000) : 0;
			
			console.log('AI思考完成，思考时长:', thinkingDuration, '秒');
			
			// 提取思考内容和最终响应
			const thinkingContent = processedContent.substring(thinkStartIndex + 7, thinkEndIndex);
			const finalResponse = processedContent.substring(thinkEndIndex + 8); // 8是'</think>'的长度
			
			// 显示最终响应，包含思考时长
			displayContent = thinkingDuration > 0 ? 
				`💭 思考完成 (${thinkingDuration}秒)\n\n${finalResponse}` : 
				finalResponse;
			
			this.setData({
				isThinking: false,
				thinkingDuration: thinkingDuration,
				thinkingContent: thinkingContent,
				finalResponse: finalResponse
			});
			
		} else if (this.data.isThinking && thinkEndIndex !== -1) {
			// 思考结束（流式接收中）
			const thinkingDuration = Math.round((Date.now() - this.data.thinkingStartTime) / 1000);
			console.log('AI思考完成，思考时长:', thinkingDuration, '秒');
			
			// 提取最终响应
			const finalResponse = processedContent.substring(thinkEndIndex + 8);
			displayContent = `💭 思考完成 (${thinkingDuration}秒)\n\n${finalResponse}`;
			
			this.setData({
				isThinking: false,
				thinkingDuration: thinkingDuration,
				finalResponse: finalResponse
			});
		} else if (this.data.isThinking) {
			// 正在思考中，继续显示思考内容
			const thinkingContent = processedContent.substring(thinkStartIndex + 7);
			displayContent = '🤔 AI正在思考中...\n\n' + thinkingContent;
		}
		
		// 更新聊天列表
		console.log('updateChatMessage - startIndex:', ctx.startIndex, 'currentList.length:', currentList.length, 'content:', displayContent);
		
		// 确保索引有效
		if (ctx.startIndex >= 0 && ctx.startIndex < currentList.length) {
			currentList[ctx.startIndex] = { 
				type: 'ai', 
				content: displayContent, 
				time: ctx.now,
				isThinking: this.data.isThinking
			};
			this.setData({ chatList: currentList });
			console.log('Updated chatList at index', ctx.startIndex, 'with content:', displayContent);
			// this.scrollToBottom();
		} else {
			console.error('Invalid startIndex:', ctx.startIndex, 'for chatList length:', currentList.length);
			// 如果索引无效，添加到列表末尾
			const newList = [...currentList, { 
				type: 'ai', 
				content: displayContent, 
				time: ctx.now,
				isThinking: this.data.isThinking
			}];
			this.setData({ chatList: newList });
			console.log('Added AI message to end of list');
			// this.scrollToBottom();
		}
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    },isLogin(callback){
      let logined = wx.getStorageSync('logined');
      if (!logined){
          utils.showConfirmModal({
            title: '提示',
            content: '为提供更好的服务，请授权获取您的基本信息',
            onConfirm: () => {
              // 确定后的操作
              //获取推荐商户id
              let merchantId = null;
              let role = null;
              wx.getStorage({
                key: 'merchantId',
                success: (res) => {
                  console.log('merchantId:', res.data); // 输出存储的值
                  merchantId = res.data;
                },
                fail: (err) => {
                  console.error('读取失败:', err);
                }
              });
              wx.getStorage({
                key: 'role',
                success: (res) => {
                  console.log('role:', res.data); // 输出存储的值
                  role = res.data;
                },
                fail: (err) => {
                  console.error('读取失败:', err);
                }
              });
              wx.getUserProfile({
                desc: '用于获取用户信息',
                success:(res) => {
                  let detail = res;

                  wx.login({
                      success: (res) => {
                        if (res.code){
                            wx.showLoading();
                            utils.request(api.AuthLoginByWeixin, {
                               code:res.code,
                               weixinFullVO:detail,
                               merchantId:merchantId,
                               role:role
                            }, 'POST').then(res => {
                                wx.hideLoading();

                                if (res.code == "0"){
                                  wx.setStorageSync('token', res.data.token);
                                  wx.setStorageSync('logined', true);
                                  callback();
                                }else{
                                      wx.showToast({
                                        title: res.message,
                                        icon:"none"
                                      })
                                }
                            })
                        }
                      },
                      fail: (e) => {
                          wx.showToast({
                            title: 'e',
                            icon:"none"
                          })
                      }
                    })
                }
              })
            },
            onCancel: () => {
              console.log("click cancel");
            }
          });
      }else{
            callback();
      }
  },
  handleConfirmModalConfirm(e){

  },handleConfirmModalCancel(e){

    }
})